//
//  YQAddAndEditorVC.m
//  NewRetail
//
//  Created by yuqin on 2019/6/28.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQAddAndEditorVC.h"
#import "YQAddAndEditorCell.h"

@interface YQAddAndEditorVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *addAndEditorTB;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) UIButton *saveBtn;

//输入框赋值
@property (nonatomic, strong) UITextField *nameTF;
@property (nonatomic, strong) UITextField *teleTF;
@property (nonatomic, strong) UITextField *addressTF;
//判断是否选中默认地址
@property (nonatomic, copy) NSString *defaultAddress;

@end

@implementation YQAddAndEditorVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.btnLeft setTitle:@"添加/编辑地址" forState:UIControlStateNormal];
    [self setupAddAndAddressUI];
    self.titleArr = @[@[@"请输入姓名",@"手机号码",@"配送地址"],@[@""]];
    self.defaultAddress = @"0";
}

- (void)setupAddAndAddressUI {
    [self.view addSubview:self.addAndEditorTB];
    self.view.backgroundColor = MainBackgroundColor;
    [self.view addSubview:self.saveBtn];
    [self.addAndEditorTB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, FIT(220)));
    }];
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kMargin_left);
        make.bottom.mas_equalTo(-FIT(150));
        make.size.mas_equalTo(CGSizeMake(ScreenWidth-2*kMargin_left, kCommitButtonHeight));
    }];
}

- (UITableView *)addAndEditorTB {
    if (!_addAndEditorTB) {
        _addAndEditorTB = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _addAndEditorTB.backgroundColor = MainBackgroundColor;
        _addAndEditorTB.delegate = self;
        _addAndEditorTB.dataSource = self;
        _addAndEditorTB.scrollEnabled = NO;
        _addAndEditorTB.bounces = NO;
        _addAndEditorTB.tableFooterView = [[UIView alloc] init];
        [_addAndEditorTB registerClass:[YQAddAndEditorCell class] forCellReuseIdentifier:YQ_AddAndEditorCell];
    }
    return _addAndEditorTB;
}

- (UIButton *)saveBtn {
    if (!_saveBtn) {
        _saveBtn = [YQViewFactory buttonWithTitle:@"保存" image:YQ_IMAGE(@"") titleColor:WhiteColor fontSize:kNormalButtonFont userBold:NO target:self sel:@selector(saveAction)];
        [_saveBtn setBackgroundImage:CommitButtonImg forState:UIControlStateNormal];
    }
    return _saveBtn;
}
#pragma mark - 保存
- (void)saveAction {
    if (isEmptyString(self.nameTF.text)) {
        [LCProgressHUD showFailure:@"请填写姓名"];
        return;
    }
    
    if (isEmptyString(self.teleTF.text)) {
        [LCProgressHUD showFailure:@"请填写手机号码"];
        return;
    }
    
    if (![LimitTextFieldNum validateCellPhoneNumber:self.teleTF.text]) {
        [LCProgressHUD showFailure:@"请输入正确手机号码"];
        return;
    }
    
    if (isEmptyString(self.addressTF.text)) {
        [LCProgressHUD showFailure:@"请填写配送地址"];
        return;
    }
    //区分是添加地址还是编辑地址
    NSDictionary *addressDict = @{@"id":self.payModel == nil?@"":self.payModel.id,
                                  @"name":self.nameTF.text,
                                  @"countryCode":@"86",
                                  @"phone":self.teleTF.text,
                                  @"addressDetail":self.addressTF.text,
                                  @"isDefault":self.defaultAddress
                                  };
    [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"address/saveOrUpdate") appendParameters:nil bodyParameters:addressDict successBlock:^(id responseObject) {
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            //保存成功并返回刷新
            [LCProgressHUD showSuccess:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failureBlock:^(NSError *error) {
        
    }];
}

#pragma mark - 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.titleArr[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return FIT(50);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0?0:FIT(24);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YQAddAndEditorCell *cell = [tableView dequeueReusableCellWithIdentifier:YQ_AddAndEditorCell forIndexPath:indexPath];
    cell.leftTextField.placeholder = self.titleArr[indexPath.section][indexPath.row];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            self.nameTF = cell.leftTextField;
        }else if (indexPath.row == 1) {
            self.teleTF = cell.leftTextField;
        }else {
            self.addressTF = cell.leftTextField;
        }
    }
    if (self.payModel  == nil) {
        
        @weakify(self);
        cell.SetDefaultAddressBlock = ^(BOOL isSelect) {
            @strongify(self);
            if (isSelect == YES) {
                self.defaultAddress = @"1";
            }else {
                self.defaultAddress = @"0";
            }
        };
        if (indexPath.section == 0) {
            cell.TextFieldEndEditorBlock = ^(NSString * _Nonnull text) {
                @strongify(self);
                if (indexPath.row == 0) {
//                    self.nameStr = text;
                    [LimitTextFieldNum limitTextFieldContentNumWith:cell.leftTextField withMaxNum:6];
                }else if (indexPath.row == 1) {
//                    self.teleStr = text;
                    cell.leftTextField.keyboardType = UIKeyboardTypeNumberPad;
                    [LimitTextFieldNum limitTextFieldContentNumWith:cell.leftTextField withMaxNum:11];
                }else {
//                    self.addressStr = text;
                }

            };
        }
    }else {
        NSArray *titleArr = @[self.payModel.name,self.payModel.phone,self.payModel.addressDetail];
        if ([self.payModel.isDefault integerValue] == 1) {
            cell.selectBtn.selected = YES;
        }else {
            cell.selectBtn.selected = NO;
        }
        @weakify(self);
        cell.SetDefaultAddressBlock = ^(BOOL isSelect) {
            @strongify(self);
            if (isSelect == YES) {
                self.defaultAddress = @"1";
                
            }else {
                self.defaultAddress = @"0";
            }
        };
        if (indexPath.section == 0) {
            cell.leftTextField.text = titleArr[indexPath.row];
//            self.nameStr = titleArr[0];
//            self.teleStr = titleArr[1];
//            self.addressStr = titleArr[2];
        }
    }
    
    if (indexPath.section == 1) {
        cell.leftTextField.text = @"设为默认地址";
        cell.leftTextField.enabled = NO;
        [cell.selectBtn setHidden:NO];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

@end
